(function()
{
	var localPrintFun = function(backfun)
	{
		this._debugOnline = true;
		this._data = {
			dpi : 203, // 打印机分辨率
			printOverFun : null,
			printer : null, // 打印机句柄，通过 new jpPrinterFun(); 赋予值
		};
	};
	/**
	 * 初始化，调入资源文件
	 */
	localPrintFun.prototype.init = function(backfun)
	{
		if (!window.jpPrinterFun)
		{
			loadJs(app.core+'/js/public/printerdriver/tsplPrinter.js', function()
			{
				loadJs(app.core+'/js/plugins/encoding-indexes.js', function()
				{
					loadJs(app.core+'/js/plugins/encoding.js', function()
					{
						window.jpPrinterFun = window.tsplPrinterFun;
						new jpPrinterFun();
						if (backfun)
							backfun();
					});
				});
			});
		}
		else
		{
			if (backfun)
				backfun();
		}
	}
	/*
	 * 打印函数（主入口函数），注意，一旦发送到打印机就在终端清空缓存，并在333毫秒后试探是否成功，失败就返回失败
	 */
	localPrintFun.prototype.print = function(para, backfun, isTryInit)
	{
		var that = this;
		if (!isTryInit)
		{
			this.init(function()
			{
				that.print(para, backfun, true);
			});
			return;
		}
		var isOnline = bleIsOnline();
		if (isOnline === null)
			return;
		else if (isOnline)
			this._doPrintFromPara(para, backfun);
		else
		{
			// 连接蓝牙，可能要等待操作
			bleConn(function(isOK, msg)
			{
				if (isOK)
				{
					that.print(para, backfun);
				}
				else
				{
					if (msg)
						layer.msg(msg);
					confirm(app.w('login.msg.blePrinterTryConn'), function()
					{
						that.print(para, backfun);
					}, function()
					{
						var msg = app.w('login.msg.blePrinterOffline');
						if (backfun)
							backfun(msg, false);
						else
							layer.msg(msg);
					});
				}
			}, 'printer');
		}
	}
	/**
	 * 取得当前打印编号(状态)
	 */
	localPrintFun.prototype._getPrintId = function()
	{
		if (!window.toAndroidApp || !window.toAndroidApp.getPrintId)
			return '_notinandroidapp';
		return window.toAndroidApp.getPrintId();
	}
	/**
	 * 发送数据
	 */
	localPrintFun.prototype._send = function(buff, backfun, tryTimes)
	{
		if (!window.toAndroidApp)
		{
			layer.msg('not in AndroidApp');
			return;
		}
		var that = this;
		if (!tryTimes)
		{
			window.toAndroidApp.sendPrintData(this._arrayBufferToBase64(buff), '');
		}
		setTimeout(function()
		{
			if (!tryTimes)
				tryTimes = 0;
			// 测试是否成功
			var reid = ' ' + that._getPrintId();
			var isOk = (reid.indexOf('-printed') >= 0);
			if (!isOk && tryTimes < 10)
			{
				that._send(null, backfun, tryTimes + 1);
				return;
			}
			var msg = isOk ? app.w('login.msg.printed') : app.w('login.msg.printFailed');
			if (backfun)
				backfun(msg, isOk);
			else
				layer.msg(msg);
			if (!isOk)
				app.play('printfailed');
		}, 333);
	}
	// /////////////////////////////////////////
	localPrintFun.prototype._arrayBufferToBase64 = function(buff)
	{
		var binary = '';
		var bytes = new Uint8Array(buff);
		var len = bytes.byteLength;
		for (var i = 0; i < len; i++)
		{
			binary += String.fromCharCode(bytes[i]);
		}
		return window.btoa(binary);
	}
	localPrintFun.prototype._doPrintFromPara = function(para, backfun)
	{
		var copy = this._toInt(para.getData.copy);
		if (!(copy > 1))
			copy = 1;
		var dx = this._toFloat(para.getData.marginBottom); // 向右偏移数据
		var dy = this._toFloat(para.getData.marginTop); // 向下偏移数据
		var pw = this._toFloat(para.getData.pageWidth);
		var ph = this._toFloat(para.getData.pageHeight);
		var da = (para.rawData + ' ').split("\n");
		var baseFontSize = 8; // 基础字体的大小
		// 打印
		this._setSize(pw, ph, function(msg, isOK)
		{
			if (backfun)
				backfun(msg, isOK);
			else
				layer.msg(msg);
		});
		var oldp = {};
		var oldc = '';
		var haveprint = false;
		for (var copyi = 1; copyi <= copy; copyi++)
		{
			if (copyi > 1)
				this._newPage();
			for (var i = 0; i < da.length; i++)
			{
				var ii = da[i].indexOf(':');
				if (ii > 0)
				{
					var h = da[i].substring(0, ii);
					var c = da[i].substring(ii + 1);
				}
				else
				{
					var h = da[i];
					var c = '';
				}
				var p = this._getParah(h);
				// 隐藏
				if (p.hidden == 'yes' || p.hidden == 'true' || p.hidden == '1')
					continue;
				// 抄写前面的
				else if (p.type == 'continue')
				{
					if (!oldp.type)
						continue;
					p = this._addPara(oldp, p);
					if (c == '')
						c = oldc;
					p.type = oldp.type;
				}
				// 以下开始正式打印 ////////////////////////
				if (p.type == 'newpage')
				{
					if (haveprint)
						this._newPage();
				}
				else if (p.type == 'multext')
				{
					haveprint = true;
					var size = this._toInt(p.fontsize) / baseFontSize;
					if (size < 1)
						size = 1;
					else
						size = size.toFixed(2);
					var lineheight = this._toFloat(p.lineheight);// 行高
					var width = this._toFloat(p.width);// 宽度
					if (lineheight < 4)
					{
						lineheight = 4 * size;
					}
					var npre = this._toInt(p.npre);// 每行字符用
					if (npre < 1)
					{
						npre = Math.round(width / (6 * size));
						if (npre < 1)
							npre = 10;
					}
					var s = '';
					var yn = npre;
					var left = this._toFloat(p.left);
					var top = this._toFloat(p.top) + dy;
					var hangn = this._toInt(p.maxhangnumber);
					if (!hangn)
						hangn = 9999;
					c = c.replace(/\\n/g, "\n");
					for (var ii = 0; ii < c.length; ii++)
					{
						if (hangn <= 0)
							break;
						var cc = c.substring(ii, ii + 1);
						s += cc;
						yn--;
						if (escape(cc).length > 1)
							yn--;
						if (yn <= 0 || ii >= c.length - 1 || cc == "\n")
						{
							// 最终以上面的函数实现
							this._text(left + dx, top + dy, size, s);
							yn = npre;
							top += lineheight;
							hangn--;
							s = '';
						}
					}
				}
				else if (p.type == 'text')
				{
					haveprint = true;
					var size = this._toInt(p.fontsize) / baseFontSize;
					if (size < 1)
						size = 1;
					else
						size = size.toFixed(2);
					this._text(this._toFloat(p.left) + dx, this._toFloat(p.top) + dy, size, c);
				}
				else if (p.type == 'line')
				{
					haveprint = true;
					var x1 = this._toFloat(p.left);
					var y1 = this._toFloat(p.top);
					var x2 = x1 + this._toFloat(p.width);
					var y2 = y1 + this._toFloat(p.height);
					this._line(x1 + dx, y1 + dy, x2 + dx, y2 + dy);
				}
				else if (p.type == 'barcode')
				{
					haveprint = true;
					var barcodetype = p.barcodetype;
					var x = this._toFloat(p.left);
					var y = this._toFloat(p.top);
					if (barcodetype == 'qrcode')
					{
						var nWidth = this._toInt(p.barcodewidth);
						var height = 0;
					}
					else
					{
						var nWidth = this._toInt(p.barcodewidth);
						var height = this._toInt(p.barcodesize);
					}
					this._barCode(barcodetype, x + dx, y + dy, nWidth, height, c);
				}
				else if (p.type == 'image')
				{
					haveprint = true;
					var x = this._toFloat(p.left);
					var y = this._toFloat(p.top);
					var w = this._toFloat(p.width);
					var h = this._toFloat(p.height);
					if (c)
						this._image(x + dx, y + dy, w, h, c);
				}
				var oldp = JSON.parse(JSON.stringify(p));
				var oldc = c;
			}
		}
		this._doPrint();
	}
	// ////////////////////////////////////////////
	// ////////////////////////////////////////////
	// 设置页面大小，也是初始化，单位毫米
	localPrintFun.prototype._setSize = function(pw, ph, printOverFun)
	{
		this._data.printer = new jpPrinterFun();
		this._data.imageSrcList = []; // 图片列表
		this._data.printer.setCls()
		this._data.printer.setSize(pw, ph);
		this._data.printer.setGap(3); // 两张纸的间隙
		this._data.printer.setCls();
		this._data.printOverFun = printOverFun;
	}
	// 打印文本，字体大小 1 - 7
	localPrintFun.prototype._text = function(x, y, fontSize, text)
	{
		this._data.printer.setText(this._m2p(x), this._m2p(y), "TSS24.BF2", 0, fontSize, fontSize, text); // / "TSS24.BF2"
	}
	// 线条
	localPrintFun.prototype._line = function(x1, y1, x2, y2)
	{
		var x = x1 < x2 ? x1 : x2;
		var width = Math.abs(x1 - x2);
		var y = y1 < y2 ? y1 : y2;
		var height = Math.abs(y1 - y2);
		if (width < height)
		{
			width = 2;
			height = this._m2p(height);
		}
		else
		{
			height = 2;
			width = this._m2p(width);
		}
		this._data.printer.setBar(this._m2p(x), this._m2p(y), width, height);
	}
	// 翻页(设置页打印数据)
	localPrintFun.prototype._newPage = function()
	{
		var that = this;
		this._dealImage(function()
		{
			that._data.printer.setPagePrint();
			that._data.printer.setCls()
		});
	}
	// 打印（设置页打印数据，并传送数据）
	localPrintFun.prototype._doPrint = function()
	{
		var that = this;
		this._dealImage(function()
		{
			that._data.printer.setPagePrint();
			that._send(that._data.printer.getData(), that._data.printOverFun);
		});
	}
	// 条形码，nWidth，单位宽度，二维码的height失效
	localPrintFun.prototype._barCode = function(type, x, y, nWidth, height, text)
	{
		if (type.toLowerCase() == 'qrcode')
		{
			this._data.printer.setQrcode(this._m2p(x), this._m2p(y), "M", nWidth, "A", text)
		}
		else
		{
			type = '128'; // 暂时强制使用这种方式
			this._data.printer.setBarCode(this._m2p(x), this._m2p(y), type, height, 0, 0, nWidth, nWidth, text);
		}
	}
	// 图片（先加入列表）
	localPrintFun.prototype._image = function(x, y, width, height, src)
	{
		this._data.imageSrcList.push({
			x : this._m2p(x),
			y : this._m2p(y),
			width : this._m2p(width),
			height : this._m2p(height),
			src : src,
		});
	}
	// ///////////////////////// 以下是私有函数 ///////////////////////////////////
	// 毫米到点的转换
	localPrintFun.prototype._m2p = function(mm)
	{
		return Math.round(this._data.dpi / 25.4 * mm);
	}
	// 处理图片
	localPrintFun.prototype._dealImage = function(backfun)
	{
		var that = this;
		var s = this._data.imageSrcList.shift();
		if (!s)
		{
			backfun();
			return;
		}
		if (s)
		{
			var img = new Image();
			img.src = s.src;
			// showMsg(s.src);
			img.onload = function()
			{
				if (!s.width || !s.height)
				{
					s.width = img.width;
					s.height = img.height;
				}
				var w = s.width;
				var h = s.height;
				for (var ik = 1; ik <= 16; ik++)
				{
					if (w <= ik * 128)
					{
						w = ik * 128;
						break;
					}
				}
				var ctx = that._getCanvasContext(w, h);
				ctx.drawImage(img, 0, 0);
				try
				{
					var res = ctx.getImageData(0, 0, w, h);
					that._data.printer.setBitmap(s.x, s.y, 1, res);
					that._dealImage(backfun);
				}
				catch (err)
				{
					that._dealImage(backfun);
				}
			};
			img.onerror = function()
			{
				// 直接跳过
				that._dealImage(backfun);
			};
		}
	}
	// 
	localPrintFun.prototype._getCanvasContext = function(width, height)
	{
		var canvas = document.createElement('canvas');
		canvas.style.width = width + 'px';
		canvas.style.height = height + 'px';
		canvas.width = width;
		canvas.height = height;
		return canvas.getContext('2d');
	}
	// 以后面的优先（后面的覆盖前面的）
	localPrintFun.prototype._addPara = function(a, b)
	{
		var c = JSON.parse(JSON.stringify(a));
		for ( var k in b)
		{
			if (b[k] !== undefined)
				c[k] = b[k];
		}
		return c;
	}
	localPrintFun.prototype._getParah = function(s)
	{
		var re = {};
		var a = s.split(',');
		for (var i = 0; i < a.length; i++)
		{
			var ii = a[i].indexOf('=');
			if (ii > 0)
			{
				re[a[i].substring(0, ii)] = a[i].substring(ii + 1);
			}
		}
		return re;
	}
	localPrintFun.prototype._toInt = function(s)
	{
		var r = parseInt((s + ' ').trim());
		if (!(r > 0 || r < 0))
			r = 0;
		return r;
	}
	localPrintFun.prototype._toFloat = function(s)
	{
		var r = parseFloat((s + ' ').trim());
		if (!(r > 0 || r < 0))
			r = 0.0;
		return r;
	}
	window.localPrint = new localPrintFun();
}());
